<template>
  <div class="wms-action-buttons">
    <template v-for="(action, index) in visibleActions" :key="action.type">
      <!-- 权限控制按钮 -->
      <el-button
        v-auth="action.permission"
        :type="action.buttonType || 'primary'"
        :size="size"
        :plain="action.plain"
        :round="action.round"
        :circle="action.circle"
        :loading="action.loading"
        :disabled="isActionDisabled(action)"
        :icon="action.icon"
        :link="action.link"
        :text="action.text"
        :class="getButtonClass(action)"
        @click="handleAction(action)"
      >
        {{ action.label }}
      </el-button>

      <!-- 按钮间分隔符 -->
      <el-divider
        v-if="showDivider && index < visibleActions.length - 1"
        direction="vertical"
        class="wms-action-buttons__divider"
      />
    </template>

    <!-- 更多操作下拉菜单 -->
    <el-dropdown
      v-if="moreActions.length > 0"
      :size="size"
      :trigger="dropdownTrigger"
      :placement="dropdownPlacement"
      @command="handleDropdownAction"
    >
      <el-button :type="moreButtonType" :size="size" :plain="moreButtonPlain">
        更多
        <el-icon class="el-icon--right">
          <ArrowDown />
        </el-icon>
      </el-button>

      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item
            v-for="action in moreActions"
            :key="action.type"
            :command="action"
            :disabled="isActionDisabled(action)"
            :divided="action.divided"
            :icon="action.icon"
          >
            {{ action.label }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue";
import { ArrowDown } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import { COMMON_ACTIONS } from "../constants/actions";

/**
 * 操作按钮配置接口
 */
interface WmsActionConfig {
  /** 操作类型(唯一标识) */
  type: string;
  /** 按钮文本 */
  label: string;
  /** 按钮类型 */
  buttonType?: "primary" | "success" | "warning" | "danger" | "info";
  /** 图标 */
  icon?: string;
  /** 权限标识 */
  permission?: string | string[];
  /** 是否显示 */
  show?: boolean | ((row?: any, index?: number) => boolean);
  /** 是否禁用 */
  disabled?: boolean | ((row?: any, index?: number) => boolean);
  /** 是否朴素按钮 */
  plain?: boolean;
  /** 是否圆角按钮 */
  round?: boolean;
  /** 是否圆形按钮 */
  circle?: boolean;
  /** 是否加载中 */
  loading?: boolean;
  /** 是否链接按钮 */
  link?: boolean;
  /** 是否文字按钮 */
  text?: boolean;
  /** 自定义样式类 */
  className?: string;
  /** 是否放入更多菜单 */
  more?: boolean;
  /** 下拉菜单项分割线 */
  divided?: boolean;
  /** 确认对话框配置 */
  confirm?: {
    title?: string;
    message: string;
    type?: "warning" | "info" | "success" | "error";
  };
  /** 操作前置钩子 */
  beforeAction?: (row?: any, index?: number) => boolean | Promise<boolean>;
}

/**
 * WMS操作按钮组件属性接口
 */
interface WmsActionButtonsProps {
  /** 操作配置列表 */
  actions: WmsActionConfig[];
  /** 按钮尺寸 */
  size?: "large" | "default" | "small";
  /** 数据行(用于权限和状态判断) */
  row?: any;
  /** 行索引 */
  index?: number;
  /** 最大显示按钮数 */
  maxButtons?: number;
  /** 是否显示分隔符 */
  showDivider?: boolean;
  /** 下拉菜单触发方式 */
  dropdownTrigger?: "hover" | "click" | "contextmenu";
  /** 下拉菜单位置 */
  dropdownPlacement?:
    | "top"
    | "top-start"
    | "top-end"
    | "bottom"
    | "bottom-start"
    | "bottom-end";
  /** 更多按钮类型 */
  moreButtonType?: "primary" | "success" | "warning" | "danger" | "info";
  /** 更多按钮是否朴素 */
  moreButtonPlain?: boolean;
}

/**
 * WMS操作按钮组件事件接口
 */
interface WmsActionButtonsEmits {
  /** 操作按钮点击事件 */
  action: [type: string, row?: any, index?: number];
}

// 组件属性定义
const props = withDefaults(defineProps<WmsActionButtonsProps>(), {
  size: "small",
  maxButtons: 3,
  showDivider: false,
  dropdownTrigger: "hover",
  dropdownPlacement: "bottom-end",
  moreButtonType: "info",
  moreButtonPlain: true,
});

// 组件事件定义
const emit = defineEmits<WmsActionButtonsEmits>();

// 可见的操作列表
const visibleActions = computed(() => {
  return props.actions
    .filter((action) => {
      // 检查显示条件
      if (typeof action.show === "function") {
        return action.show(props.row, props.index);
      }
      return action.show !== false;
    })
    .filter((action) => !action.more)
    .slice(0, props.maxButtons);
});

// 更多操作列表
const moreActions = computed(() => {
  const remainingActions = props.actions
    .filter((action) => {
      // 检查显示条件
      if (typeof action.show === "function") {
        return action.show(props.row, props.index);
      }
      return action.show !== false;
    })
    .filter((action) => action.more || false);

  // 如果超过最大按钮数，剩余的放入更多菜单
  const overflowActions = props.actions
    .filter((action) => {
      if (typeof action.show === "function") {
        return action.show(props.row, props.index);
      }
      return action.show !== false;
    })
    .filter((action) => !action.more)
    .slice(props.maxButtons);

  return [...remainingActions, ...overflowActions];
});

/**
 * 判断操作是否禁用
 */
function isActionDisabled(action: WmsActionConfig): boolean {
  if (typeof action.disabled === "function") {
    return action.disabled(props.row, props.index);
  }
  return action.disabled || false;
}

/**
 * 获取按钮样式类
 */
function getButtonClass(action: WmsActionConfig): string {
  let className = "wms-action-buttons__button";

  if (action.className) {
    className += ` ${action.className}`;
  }

  // 根据操作类型添加特定样式
  if (action.type) {
    className += ` wms-action-buttons__button--${action.type}`;
  }

  return className;
}

/**
 * 处理操作按钮点击
 */
async function handleAction(action: WmsActionConfig): Promise<void> {
  try {
    // 执行前置钩子
    if (action.beforeAction) {
      const canProceed = await action.beforeAction(props.row, props.index);
      if (!canProceed) {
        return;
      }
    }

    // 显示确认对话框
    if (action.confirm) {
      const confirmed = await showConfirmDialog(action.confirm);
      if (!confirmed) {
        return;
      }
    }

    // 触发操作事件
    emit("action", action.type, props.row, props.index);
  } catch (error) {
    console.error(`执行操作 ${action.type} 时发生错误:`, error);
  }
}

/**
 * 处理下拉菜单操作
 */
function handleDropdownAction(action: WmsActionConfig): void {
  handleAction(action);
}

/**
 * 显示确认对话框
 */
function showConfirmDialog(
  config: NonNullable<WmsActionConfig["confirm"]>,
): Promise<boolean> {
  return new Promise((resolve) => {
    // 使用Element Plus的MessageBox
    ElMessageBox.confirm(config.message, config.title || "确认操作", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: config.type || "warning",
      center: true,
    })
      .then(() => resolve(true))
      .catch(() => resolve(false));
  });
}

// 导出常量供外部使用
defineExpose({
  COMMON_ACTIONS,
});
</script>

<style scoped lang="scss">
.wms-action-buttons {
  display: inline-flex;
  align-items: center;
  gap: var(--wms-spacing-xs);

  &__button {
    // 通用按钮样式
    &--view {
      color: var(--wms-info-color);

      &:hover {
        color: var(--wms-info-color-dark);
      }
    }

    &--edit {
      color: var(--wms-primary-color);

      &:hover {
        color: var(--wms-primary-color-dark);
      }
    }

    &--delete {
      color: var(--wms-error-color);

      &:hover {
        color: var(--wms-error-color-dark);
      }
    }

    &--enable {
      color: var(--wms-success-color);

      &:hover {
        color: var(--wms-success-color-dark);
      }
    }

    &--disable {
      color: var(--wms-warning-color);

      &:hover {
        color: var(--wms-warning-color-dark);
      }
    }
  }

  &__divider {
    margin: 0 var(--wms-spacing-xs);
    height: 16px;
  }

  // Element Plus按钮样式定制
  :deep(.el-button) {
    padding: 4px 8px;
    font-size: 12px;
    border: none;

    &.is-text {
      padding: 2px 4px;

      &:hover {
        background-color: transparent;
      }
    }

    &.is-link {
      padding: 2px 0;
    }

    // 小尺寸按钮
    &.el-button--small {
      padding: 2px 6px;
      font-size: 11px;
    }

    // 大尺寸按钮
    &.el-button--large {
      padding: 6px 12px;
      font-size: 14px;
    }
  }

  // 下拉菜单样式
  :deep(.el-dropdown) {
    .el-button {
      .el-icon--right {
        margin-left: 4px;
      }
    }
  }

  // 响应式适配
  @media (max-width: 768px) {
    gap: var(--wms-spacing-xs);

    :deep(.el-button) {
      padding: 2px 4px;
      font-size: 11px;

      .el-icon {
        font-size: 12px;
      }
    }
  }
}
</style>
